﻿namespace Leetcode.N0013;

public class Solution
{
    public int RomanToInt(string s)
    {
        var val = 0;
        for (int i = 0; i < s.Length; i++)
        {
            switch (s[i])
            {
                case 'I':
                    val += this.ReadI(s, 'I', 'V', 'X', 1, ref i);
                    break;
                case 'V':
                    val += this.ReadV(s, 'V', 'I', 1, ref i);
                    break;
                case 'X':
                    val += this.ReadI(s, 'X', 'L', 'C', 10, ref i);
                    break;
                case 'L':
                    val += this.ReadV(s, 'L', 'X', 10, ref i);
                    break;
                case 'C':
                    val += this.ReadI(s, 'C', 'D', 'M', 100, ref i);
                    break;
                case 'D':
                    val += this.ReadV(s, 'D', 'C', 100, ref i);
                    break;
                case 'M':
                    val += this.ReadI(s, 'M', '\0', '\0', 1000, ref i);
                    break;
            }
        }
        return val;
    }

    private int ReadI(string s, char c1, char c2, char c3, int baseVal, ref int index)
    {
        var count = 1;
        for (int i = index + 1; i < s.Length; i++)
        {
            if (s[i] == c2)
            {
                count = 4;
                index++;
                break;
            }
            else if (s[i] == c3)
            {
                count = 9;
                index++;
                break;
            }
            else if (s[i] == c1)
            {
                count++;
                index++;
                continue;
            }
            else
            {
                break;
            }
        }
        return count * baseVal;
    }

    private int ReadV(string s, char c1, char c2, int baseValue, ref int index)
    {
        int count = 5;
        for (int i = index + 1; i < s.Length; i++)
        {
            if (s[i] == c2)
            {
                index++;
                count++;
            }
            else
            {
                break;
            }
        }
        return count * baseValue;

    }

}
